package com.ziyueyuwen.xiniao.controller.question.course;

import com.alibaba.fastjson.JSONObject;
import com.suyeer.basic.util.HttpResUtil;
import com.ziyueyuwen.xiniao.base.HttpResContent;
import com.ziyueyuwen.xiniao.bean.ZyLessonMessageTask;
import com.ziyueyuwen.xiniao.bean.ao.QuestionForCourseLessonAO;
import com.ziyueyuwen.xiniao.bean.page.PageData;
import com.ziyueyuwen.xiniao.bean.query.CourseQuery;
import com.ziyueyuwen.xiniao.bean.question.CourseLessonElementData;
import com.ziyueyuwen.xiniao.bean.question.CourseQuestionQuery;
import com.ziyueyuwen.xiniao.bean.vo.ZyCourseVO;
import com.ziyueyuwen.xiniao.bean.vo.ZyQuestionDataVO;
import com.ziyueyuwen.xiniao.enums.LessonModuleEnum;
import com.ziyueyuwen.xiniao.service.CourseService;
import com.ziyueyuwen.xiniao.service.MessageTaskService;
import com.ziyueyuwen.xiniao.service.QuestionCourseService;
import com.ziyueyuwen.xiniao.service.SubjectQuestionService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ziyueyuwen.xiniao.base.BaseUtil.saveErrorMsgAndData;
import static com.ziyueyuwen.xiniao.base.BaseUtil.saveSuccessMsgAndData;
import static com.ziyueyuwen.xiniao.util.ConstUtil.PARAM_COURSE_ID;
import static com.ziyueyuwen.xiniao.util.ConstUtil.PARAM_LESSON_INDEX;

/**
 * @author wancheng  on 2019/1/9.
 */
@Controller
@Validated
@RequestMapping("/question/course")
public class QuestionCourseController {

    private final static Logger logger = LoggerFactory.getLogger(QuestionCourseController.class);

    @Autowired
    CourseService courseService;
    @Autowired
    QuestionCourseService questionCourseService;
    @Autowired
    SubjectQuestionService subjectQuestionService;
    @Autowired
    private MessageTaskService messageTaskService;

    @RequestMapping(value = "/get_course.do", method = RequestMethod.POST)
    public void getCourseForQuestion(HttpServletRequest request,
                                     HttpServletResponse response,
                                     CourseQuery query) {
        HttpResContent<PageData<ZyCourseVO>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("题库-获取课程列表");
        try {
            PageData<ZyCourseVO> res = courseService.getCourseForQuestion(query);
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_course_details.do", method = RequestMethod.POST)
    public void getCourseDetails(HttpServletRequest request,
                                 HttpServletResponse response,
                                 Integer courseId) {
        HttpResContent<List<CourseLessonElementData>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("题库-获取课程的课节详情");
        try {
            List<CourseLessonElementData> details = questionCourseService.getCourseDetails(courseId);
            saveSuccessMsgAndData(hrc, details);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/update_question_for_course_lesson.do", method = RequestMethod.POST)
    public void updateCourseLessonQuestion(HttpServletRequest request,
                                           HttpServletResponse response,
                                           @Validated QuestionForCourseLessonAO updateData) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("修改课节题");
        try {
            questionCourseService.updateQuestionForCourseLesson(updateData);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_question_for_course_lesson.do", method = RequestMethod.POST)
    public void getCourseLessonQuestion(HttpServletRequest request,
                                        HttpServletResponse response,
                                        CourseQuestionQuery questionQuery) {
        HttpResContent<List<ZyQuestionDataVO>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("查看课节题");
        try {
            List<ZyQuestionDataVO> data = questionCourseService
                    .getQuestionOfCourseLesson(
                            questionQuery.getCourseId(),
                            questionQuery.getLessonIndex(),
                            questionQuery.getLessonQuestionType(),
                            questionQuery.getQuestionGroup());
            saveSuccessMsgAndData(hrc, data);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_class_room_test.do", method = RequestMethod.POST)
    public void getClassRoomTest(@Validated CourseQuestionQuery questionQuery) {
        HttpResContent<List<Map<String, Integer>>> hrc = new HttpResContent<>("题库-获取课中互动");
        List<ZyQuestionDataVO> data = questionCourseService
                .getQuestionOfCourseLesson(
                        questionQuery.getCourseId(),
                        questionQuery.getLessonIndex(),
                        questionQuery.getLessonQuestionType());

        List<Integer> group = new ArrayList<>();
        if (data != null) {
            Map<Integer, List<ZyQuestionDataVO>> roomMap = data.stream().collect(Collectors.groupingBy(ZyQuestionDataVO::getQuestionGroup));
            group = new ArrayList<>(roomMap.keySet()).stream().sorted(Integer::compare).collect(Collectors.toList());
        }
        List<Integer> retList = null;
        try {
            retList = subjectQuestionService.listClassroomTestLimitTime(questionQuery.getCourseId(), questionQuery.getLessonIndex());
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, Integer>> res = new ArrayList<>(5);
        for (int i = 0; i < group.size(); i++) {
            Map<String, Integer> groupLimit = new HashMap<>(2);
            groupLimit.put("group",group.get(i));
            if (CollectionUtils.isNotEmpty(retList)){
                try{
                    groupLimit.put("limit",retList.get(i));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            res.add(groupLimit);
        }
        hrc.printLogAndResponse(res);
    }

    @RequestMapping(value = "/get_answer_order.do", method = RequestMethod.POST)
    public void getAnswerOrder(@RequestParam(PARAM_COURSE_ID) Integer courseId,
                               @RequestParam(PARAM_LESSON_INDEX) Integer lessonIndex) throws Exception {
        HttpResContent<JSONObject> hrc = new HttpResContent<>("获取套题作答要求");
        JSONObject data = subjectQuestionService.getAnswerOrder(courseId, lessonIndex);
        List<ZyLessonMessageTask> list = messageTaskService.getByCourseIdAndLessonIndex(courseId, lessonIndex, LessonModuleEnum.HOMEWORK);
        data.put("haveReleaseHomework", list.size() > 0);
        hrc.printLogAndResponse(data);
    }

    @RequestMapping(value = "/update_course_lesson_count_identity.do", method = RequestMethod.POST)
    public void addCourseLessonNum(HttpServletRequest request,
                                   HttpServletResponse response,
                                   Integer courseId) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("添加课程课节数");
        try {
            courseService.updateCourseLessonCountIdentity(courseId);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            HttpResUtil.writeResult(hrc, true);
        }
    }
}
